import store from '@/store'
import _projectConfig from '@/app.config.js'
// 根据环境切换配置
let _baseURL = _projectConfig.baseURL[_projectConfig.currentEnv];
let systemInfo = uni.getSystemInfoSync()
// 同时发送异步代码的次数，防止一次点击中有多次请求
let ajaxTimes = 0;
let showLoading = false
import md5Libs from "uview-ui/libs/function/md5";
const instance = function () {
    let that = this;
    this.get = function (_api, data, _headers, loading = false) {
        return _request(_api, {
            method: 'GET',
            data: data || {}
        }, _headers);
    };

    this.post = function (_api, data, _headers, loading = false) {
        return _request(_api, {
            method: 'POST',
            data: data || {}
        }, _headers);
    };

    this.put = function (_api, data, _headers, loading = false) {
        return _request(_api, {
            method: 'PUT',
            data: data || {}
        }, _headers);
    };

    this.delete = function (_api, data, _headers, loading = false) {
        return _request(_api, {
            method: 'DELETE',
            data: data || {}
        }, _headers);
    };
};

// 请求方法
const _request = (_api, _config, _headers, loading = false) => {
    return new Promise(async (resolve, reject) => {
		let randomNum = Math.floor(Math.random() * 1000000).toString();
		while (randomNum.length < 6) {
		    randomNum = "0" + randomNum;
		}
        try {
            let _header = {
                ..._headers,
				'noncestr':randomNum,
				'content-type':'application/json',
				'timestamp':Date.now(),
				'traceid':uni.$utils.uuid(),
				// 'did':systemInfo.deviceId || 'no_did',
				'did':'no_did',
				
				// #ifdef MP-WEIXIN|| H5
				'version':systemInfo.appVersion,
				// #endif
				
				// #ifdef APP
				'version':systemInfo.appWgtVersion,
				// #endif
				
				// #ifdef MP-WEIXIN
				'platform': 'miniapp',
				// #endif
				
				// #ifdef APP 
				'platform':systemInfo.platform.toLowerCase(),
				// #endif
				
				// #ifdef H5
				// 'platform':systemInfo.platform.toLowerCase(),
				// 'platform': 'miniapp',
				'platform':'web',
				// #endif
            }
			// 获取token
			if(store.state.user.userInfo.token){
				 _header['token'] = store.state.user.userInfo.token;
			}
			
			_header.sign = sign(_header,_config.method,_config.data);
            // 基础请求配置
            let _baseConfig = {
                url: _baseURL.API_URL,
                data: {},
                header: _header
            };

            Object.assign(_baseConfig, _config);

            // 拼接请求地址
            _baseConfig.url = (_baseConfig.url + _api);
			
            // 加载动画
            if (loading) {
                setTimeout(function () {
                    if (ajaxTimes > 1 && !showLoading) {
                        showLoading = true
                        uni.showLoading();
                    }
                }, 500);
                ajaxTimes++;
            }

            // 执行请求
            uni.request({
                ..._baseConfig,
                success: (res) => {
                    if (loading) { uni.hideLoading() }
                    hideLoading()
                    _responseInterceptor(res);
                },
                fail: (err) => {
                    if (loading) { uni.hideLoading() }
                    hideLoading()
                }
            });
        } catch (err) {
            if (loading) { uni.hideLoading() }
            reject(err);
        };

        // 响应拦截器
        /**
            TODO:
            - 根据状态码判断成功还是失败
            - 返回各状况下正确的值
         */
		
        const _successedStatusCode = [200, 201, 204];
        const _responseInterceptor = (res) => {
            if (res.data.code && res.data.code == 40003) {
				store.commit("user/SET_USER_INFO", {})
                // 判断有更新数据的时候不跳登录先弹窗
                setTimeout(() => {
                    const pages = getCurrentPages(); //当前页
                    if (pages[pages.length - 1].route != 'subPackages/my/login/index') {
						uni.navigateTo({
							url: '/subPackages/my/logon/index'
						})
                    }
                }, 500);
                return;
            } else {
                if (res.data.code == 200) {
                    resolve(res.data);
                } else {
					setTimeout(() => {
						uni.showToast({
							icon: 'none',
							title:  res.data.message,
							duration:2000,
						})
					}, 500);
                    reject(res.data);
                }
            }
        };
    });
};

// 取消加载动画
function hideLoading() {
    setTimeout(function () {
        ajaxTimes--;
        if (ajaxTimes < 0) ajaxTimes = 0
        if (ajaxTimes == 0) {
            showLoading = false
            uni.hideLoading();
        }
    }, 100);
};

function sign(_header,method,data){
	// 构建请求头验签参数
	let headers = _header
	let headerObj = {};
	let excludeHeaders = new Set(['sign','User-Agent','content-type'])
		
	for(let key in headers){
		if (!excludeHeaders.has( key)) {
		  headerObj[key] = headers[key];
		}
	}
	// console.log('headerObj===========>',headerObj)
	let headerKeys = Object.keys(headerObj).sort();
	let headerPair = [];
	for (let i = 0; i < headerKeys.length; i++) {
	  let key = headerKeys[i];
	  headerPair.push(key + '=' + headerObj[key]);
	}
	let headerSignTemp = headerPair.join('&')
	// console.log(headerSignTemp)
	// 构建请求体验签参数
	let requestMethod = method
	
	let bodyPair = []
	let bodyParams = {}
	let bodyKeys = []
	if (requestMethod == 'POST') {
	    let bodyJsonData = data
	    for (let key in bodyJsonData) {
	        let value = bodyJsonData[key]
	        if (value !== '') {
	            // 如果值是对象或数组，将其转换为JSON字符串
	            if (typeof value === 'object' || Array.isArray(value)) {
	                // console.log(key + JSON.stringify(value))
	                value = JSON.stringify(value);
	            }
	            bodyParams[key] = value
	            bodyKeys.push(key)
	        }
	    }
	} else {
	    var queryParams = data
	    // queryParams.each((item) => {
	    //     bodyParams[item.key] = item.value
	    //     bodyKeys.push(item.key)
	    // });
		
		// for(let key in queryParams ){
		// 	bodyKeys.push(key)
		// }
		
		for (let key in queryParams) {
		    let value = queryParams[key]
		    if (value !== '') {
		        // 如果值是对象或数组，将其转换为JSON字符串
		        if (typeof value === 'object' || Array.isArray(value)) {
		            // console.log(key + JSON.stringify(value))
		            value = JSON.stringify(value);
		        }
		        bodyParams[key] = value
		        bodyKeys.push(key)
		    }
		}
	}
	bodyKeys.sort()
	// console.log(bodyParams)
	for (let i = 0, len = bodyKeys.length; i < len; i++) {
	    let k = bodyKeys[i]
	    // console.log(bodyParams[k])
	    bodyPair.push(k + '=' + bodyParams[k])
	}
	let bodySignTemp = bodyPair.join('&')
	// console.log('bodySignTemp===================>',bodySignTemp)
	// console.log('headerSignTemp==========================>',headerSignTemp)
	// 获取密钥
	let secret = 'vmpMaPymdxxLgeUmC46X'
	// 生成签名
	let sign = md5Libs.md5(bodySignTemp + headerSignTemp + secret).toString()
	// console.log('sign=============>',sign)
	// 设置签名
	return sign
	// headers.upsert({key: 'sign', value: sign})
}

export default instance